package com.dospyer.provider.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.dospyer.provider.api.ProviderApi;
import com.dospyer.provider.api.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.UUID;

@Slf4j
@RestController
public class ProviderController implements ProviderApi {

    @Override
    @SentinelResource(value = "sayHello", blockHandler = "sayHelloBlockHandler", fallback = "sayHelloFallback")
    public String sayHello(@PathVariable("id") Long id, String name, Integer age) {
//        try {
//            Thread.sleep(5000);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
        if (id % 2 == 0) {
            throw new RuntimeException("测试异常");
        }
        String uuid = UUID.randomUUID().toString();
        String result = "{'msg': 'hello, " + name + "(" + id + age + ")-" + uuid + "'}";
        log.info("正常访问 sayHello ，返回：{}", result);
        return result;
    }

    @Override
    public String createUser(@RequestBody User user) {
        log.info("正常访问 createUser ，请求：{}", user);
        return "{'msg': 'success'}";
    }

    /**
     * 接口抛出限流或降级时的处理逻辑
     * <p>
     * 注意: 方法参数、返回值要与原函数保持一致
     *
     * @return
     */
    public String sayHelloBlockHandler(Long id, String name, Integer age, BlockException e) {
        log.error("sayHelloBlockHandler", e);
        return "sayHelloFallback : id=" + id + "，name=" + name + "，age=" + age;
    }

    /**
     * 接口运行时抛出的异常提供 fallback 处理，建议使用统一的异常捕获
     * <p>
     * 注意: 方法参数、返回值要与原函数保持一致
     *
     * @return
     */
    public String sayHelloFallback(Long id, String name, Integer age, Throwable e) {
        log.error("sayHelloFallback", e);
        return "sayHelloFallback : id=" + id + "，name=" + name + "，age=" + age;
    }
}